package com.connect.server.handler;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;

import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;

/**
 * 安全策略文件服务器入口
 * @author chzcb
 * @email chzcb2008@gmail.com
 * @date 2011-8-31
 *
 */
public class SecuityFileHandler implements IDataHandler, IConnectHandler {

	private ByteBuffer buffer = ByteBuffer.allocate(1024);
	public boolean onConnect(INonBlockingConnection arg0) throws IOException,
			BufferUnderflowException, MaxReadSizeExceededException {
		return true;
	}
	 public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException {
	        try {
	            int abailable = nbc.available();
	            if (abailable > 0) {
	                if (nbc.indexOf("<policy-file-request/>", "UTF-8") != -1) {
	                    nbc.read(buffer);
	                    buffer.clear();
	                    String xml = "<cross-domain-policy>";
	                    xml = xml + "<allow-access-from domain=\"*\" to-ports=\"3500,6666,8888\" />";
	                    xml = xml + "</cross-domain-policy>";
	                    nbc.write(xml + "\0");
	                    return true;
	                }
	            }
	        } catch (Exception ex) {
	            System.out.println("ReceiveDataException: " + ex.getMessage());
	        }
	        return true;
	    }

}
